package com.util;
import java.sql.*;
/**
 * @author Mathison
 * @Title: DBConn
 * @Package: com.util
 * @Description: Connect to mysql database;连接至MySQL数据库
 * @date 2021/11/15 15:46
 **/



public class DBConn {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/onlineShop?useUnicode=true&characterEncoding=UTF-8";

    static final String USER = "root";
    static final String PASS = "123";

    private static Connection conn = null;
    private static ResultSet rs = null;
    private static PreparedStatement ps = null;


    //初始化，连接数据库
    public static void init() {
        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (Exception e) {
            System.out.println("init fail");
            e.printStackTrace();
        }
    }

    //    selectSql
    public static ResultSet selectSql(String sql) {
//        System.out.println(sql);
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("sql数据库查询异常");
            e.printStackTrace();
        }

        return rs;
    }

    //count
    public static int countSql(String sql){
        int count=0;
//        System.out.println(sql);
        try{
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
            if(rs.next()){
                count = rs.getInt(1);
            }
        }catch (SQLException sqlException){
            sqlException.printStackTrace();
        }
        return count;
    }

    //    addUpdDel
    public static int addUpdDel(String sql) {
        int i = 0;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            i = ps.executeUpdate();
        } catch (SQLException e) {
            //TOD0 Auto - generated catch block
            System.out.println("sq1数据库増删改异常");
            e.printStackTrace();
        }
        return i;

    }

    //    closeConn
    public static void closeConn() {
        try {
            ps.close();
            rs.close();
            conn.close();
        } catch (SQLException e) {
            // TODO Auto - generated catch block
            System.out.println("sq1数据库关闭异常");
            e.printStackTrace();
        }
    }
}
